<!-- AI模板 -->
<template>
  <div class="dashboard-editor-container">
    <div class="xxx">
      <div style="display:flex;justify-content:space-between;">
        <partitionTree 
        :nodeData="nodeData" 
        :DepartmentList="DepartmentList"
        :addTemplate="true" 
        :defaultProps="{children: 'Children', label: 'Name'}" 
        :expandArray="expandArray" 
        :defaultExpandAll="false" 
        @handleNodeClick="handleNodeClick" 
        ref="partitionTree" 
        @toggleVisibility="toggleVisibility"
        @addDepartment="getData">
        </partitionTree>
        <div :style="{ width: containerWidth}"  class="box" style="background:#fff;padding:16px;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
          <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset">
          </connsearch>
          <el-button type="primary" @click="addAssets">添加资产</el-button>
          <el-button type="success" @click="exportFollow">导出资产</el-button>
          <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
            <el-table-column label="序号" width="80" type="index" :index='(index) => { return (index + 1) + (pageNum - 1) * pageSize }'> </el-table-column>
            <el-table-column label="部门" prop="DepartmentID" width="120"  :formatter="DepartmentName" show-overflow-tooltip></el-table-column>
            <el-table-column label="资产名称" prop="DeviceName" width="160"  show-overflow-tooltip></el-table-column>
            <el-table-column label="资产编码" prop="DeviceCode" width="120"  show-overflow-tooltip></el-table-column>
            <el-table-column label="资产类型" prop="DeviceType" width="120"   show-overflow-tooltip></el-table-column>
            <el-table-column label="核心资产" prop="Level" width="80"   :formatter="ISCore" show-overflow-tooltip></el-table-column>
            <el-table-column label="MAC地址" prop="HardID" width="160"  show-overflow-tooltip></el-table-column>
            <el-table-column label="IP地址" prop="DeviceIP" width="140"  show-overflow-tooltip></el-table-column>
            <el-table-column label="认证模式" prop="RealnameType"   :formatter="ISauthentication" show-overflow-tooltip></el-table-column>
            <el-table-column label="识别模式" prop="RelnameID"   :formatter="ISdistinguish" show-overflow-tooltip></el-table-column>
            <el-table-column label="关联员工" prop="UserName" width="120"   show-overflow-tooltip></el-table-column>
            <el-table-column label="手机号码" prop="Phone" width="120"  show-overflow-tooltip></el-table-column>
            <el-table-column label="计算机名称" prop="ComputerName" width="120"   show-overflow-tooltip></el-table-column>
            <el-table-column label="操作系统" prop="OsInfo"  show-overflow-tooltip></el-table-column>
            <el-table-column label="生产厂商" prop="Factory"   show-overflow-tooltip></el-table-column>
            <el-table-column label="注册时间" prop="CreateTime" width="160px"  show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="180px"  fixed="right" >
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="changeModer(scope.row)">修改</el-button>
                <el-button type="danger" size="mini"  @click="deleteModer(scope.row)">删除</el-button>
                <!-- <el-button size="mini" type="success" @click="detailsChange(scope.row)">详情</el-button> -->
                <!-- <el-button size="mini" type="danger" @click="deleteModer(scope.row)">迁移</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination 
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" 
            :current-page=pageNum
            :page-size=pageSize
            background 
            layout="total, prev, pager, sizes, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 新增资产弹窗 -->
    <newAssetsAdded :moderVisible="moderVisible" :Action="Action" :Moder="Moder" @submit="submit" @cancel="cancel"></newAssetsAdded>
    <el-dialog v-el-drag-dialog title="资产详情" :close-on-click-modal="false" :visible.sync="dialogTableVisible"  width="70%" top="5vh">
      <assetsInfo :Moder="Moder"></assetsInfo> 
      <span slot="footer" class="dialog-footer">
        <el-button type="info" @click="dialogTableVisible = false;">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { connrequest } from '@/api/firstPage'
import connsearch from "@/components/connSearch";
import { parseTime, toTree} from '@/utils/index'
import elDragDialog from "@/directive/el-drag-dialog"; 
import partitionTree from "@/components/partitionTree";  
import assetsInfo from "@/components/assetsInfo"
import newAssetsAdded from "./components/newAssetsAdded"
export default {
  directives: { elDragDialog },
  components: {
    partitionTree,
    assetsInfo,
    connsearch,
    newAssetsAdded
  },
  data() {
    let that = this
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      containerWidth: 'calc(100% - 275px)',
      tableData: [],
      nodeData: [],
      DepartmentList: [],
      DeviceList:[],
      RoleList: [],
      expandArray: [],
      Action: 1,
      Moder: {},
      imageUrl: '',
      Schooledit: false,
      moderVisible: false,
      dialogTableVisible: false,
      reSource: [],
      partitionList: [],
      choseArea: {},
      searchform: {},
      
      formOptions: [
        {
          col: 7,
          label: "资产名称", // label文字
          prop: "DeviceName", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入资产名称,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceName = val
            }
          }
        },
        {
          col: 7,
          label: "资产编码", // label文字
          prop: "DeviceCode", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入资产编码,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceCode = val
            }
          }
        },
        {
          col: 7,
          label: "MAC地址", // label文字
          prop: "DeviceMAC", // 字段名
          element: "el-input", // 指定elementui组件
          initValue: "", // 字段初始值,
          placeholder: "请输入MAC地址,支持模糊查询。", // elementui组件属性
          maxlength: 50,
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.DeviceMAC = val
            }
          }
        }
      ]
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  methods: {
    DepartmentName(row){
      return this.DepartmentList.find(item => item.ID === row.DepartmentID)?.Name || '未知部门'
    },
    ISCore(row){
      return row.Level === 1 ? '普通' : "核心"
    },
    ISauthentication(row){
      return row.RealnameType === 1 ? '安装代理' : '扫描识别'
    },
    ISdistinguish(row){
      return row.RelnameID === 1 ? 'mac' : (row.RelnameID === 2 ? 'ip' : 'mac + ip')
    },
    async getData() {
      const res = await connrequest('GetDepartmentDeviceSumTree')
      res.Data.Name = res.Data.RootName
      let arr = toTree(res.Data.Department, res.Data.RootName)
      this.setDisable(1, arr , 4)
      this.nodeData = arr
      this.expandArray = [arr?.[0]?.Name]
      this.DepartmentList = res.Data.Department
      this.GetDictArea(this.choseArea)
    },
    // 超过3级,不能选中,子级分类最多4级
    /**
     * count: 当前层级
     * data: 当前层级的数据
     * maxNum: 最多不能超过几级
    */
    setDisable (count, data, maxNum) {
      if (count > maxNum) { //最多几级就写几
        data.forEach(v => {
          v.disabled = true // 超过设定的最大级数,给这一集的数据添加disabled属性
        })
      } else {
        data.forEach(v => {
          if (v.Children && v.Children.length) {
            count++
            this.setDisable(count, v.Children, maxNum)
          }
        })
      }
    },
    detailsChange(row){
      this.Moder = {
        ...row 
      }
      // this.$router.push({ path: '/asset/assetDetails', query: { Moder: this.Moder } });
      this.$router.push({ path: '/asset/assetDetails' });
      sessionStorage.setItem('detailStatus',JSON.stringify(this.Moder))
      // this.dialogTableVisible = true
    },
    async GetDictArea(obj){
      const data = {
        Paging:{
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          DeviceName: this.searchform?.DeviceName || '',
          DeviceCode: this.searchform?.DeviceCode || '',
          DeviceMAC: this.searchform?.DeviceMAC || '',
          Status: 0,
          ...obj
        }
      }
      const res = await connrequest('GetDevice', data)
      res.Data.map(item => {
        item.CreateTime = parseTime(item.CreateTime)
      })
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    handleNodeClick(nodeData){
      this.choseArea = {DepartmentID: nodeData.data.ID}
      this.GetDictArea(this.choseArea)
    },
    async exportFollow(){
      const data = {
        Data: {}
      }
      const res = await connrequest('ExportDevice', data)
      let softwareName = res.Data.FileName
      const a = document.createElement('a');
      a.style.display = 'none';
      // a.target = '_blank';
      a.href = softwareName;
      // a.download = softwareName;
      a.click();
      a.remove();
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = {...val}
      // if(this.searchform.timeRange){
      //   this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      // }
      this.getData()
    },
    // 重置
    reset(){
      this.pageNum = 1
      this.formOptions = this.formOptions.map( item => {
        item.initValue = ""
        return item
      })
      this.searchform = {}
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    addAssets(){
      this.Action = 1
      this.moderVisible = true
      this.Moder = {Level: 1, RealnameType: 1, RelnameID: 1, LogLevel: 1, Role: '员工', StartDate: new Date().getTime() }
    },
    changeModer(row){
      this.Action = 2
      this.Moder = {...row, StartDate: row.StartDate * 1000, UseName: row.UserName}
      this.moderVisible = true
    },
    deleteModer(row){
      this.$confirm('此操作将永久删除该资产, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const data = {
          Data: [row.DeviceUUID]
        }
        const res = await connrequest('DeleteDevice', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    cancel(){
      this.moderVisible = false
    },
    async submit(Moder, Action){
      const data = {
        Data: {
          ...Moder,
          StartDate: Math.round(Moder.StartDate / 1000)
        }
      }
      const res = await connrequest(Action === 1 ? 'AddDevice' : 'ModifyDevice', data)
      if(res.Status.StatusCode === 0){
        this.$message.success(Action === 1 ? '新增成功' : '修改成功')
        this.moderVisible = false
        this.getData()
      }
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetDictArea(this.choseArea)
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetDictArea(this.choseArea)
    },
    toggleVisibility(isHidden) { 
      if(isHidden)
        this.containerWidth = '100%';
      else 
        this.containerWidth = 'calc(100% - 275px)';
    }
  }
};
</script>
<style scoped>
.box {
  background-color: lightblue;
  transition: width 0.5s; /* 添加过渡动画 */
}
::v-deep .el-progress-bar {
  width: 70%; /* 设置进度条的宽度 */
  /* 添加其他样式属性 */
}
::v-deep .el-descriptions__header{
  margin-bottom: 10px;
}
.image-slot{
  cursor: pointer;
}

  ::v-deep .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
  .avatar {
    width: 50px;
    height: 50px;
    display: block;
  }
</style>
